/*
 * Copyright (C) 2015-2017 Alibaba Group Holding Limited
 */

#include "ls_osa.h"
#include "ali_crypto.h"

#define log_err(_f, ...) \
    ls_osa_print("E %s %d: "_f, __FUNCTION__, __LINE__, ##__VA_ARGS__)

#define TEST_DATA_SIZE (141)
uint8_t _g_test_data[TEST_DATA_SIZE] = {
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01,
   0x02, 0x03, 0x04, 0x05, 0x13
};

// Reference Hash result
static uint8_t hash_sha256[SHA256_HASH_SIZE] = {
    0x3b, 0x7f, 0x52, 0xae, 0x5b, 0xe8, 0x09, 0x19, 0x02, 0x1a,
    0x83, 0x8d, 0xcc, 0xc6, 0x01, 0xc3, 0x76, 0x41, 0x22, 0x64,
    0x4b, 0x1c, 0x35, 0xa2, 0x9d, 0xd3, 0xc5, 0x76, 0x36, 0xd7,
    0xda, 0x5f
};

uint32_t hash_example(void)
{
    uint32_t result;
    void *   hash_ctx = NULL;
    size_t   hash_ctx_size;
    uint8_t  hash[MAX_HASH_SIZE];

    result = ali_sha256_get_ctx_size(&hash_ctx_size);
    if (result != ALI_CRYPTO_SUCCESS) {
        log_err("get ctx size fail\n");
    }

    hash_ctx = ls_osa_malloc(hash_ctx_size);
    if (hash_ctx == NULL) {
        log_err("malloc fail\n");
        return -1;
    }

    result = ali_sha256_init(hash_ctx);
    if (result != ALI_CRYPTO_SUCCESS) {
        log_err("init fail\n");
        goto cleanup;
    }

    result = ali_sha256_update(_g_test_data, 13, hash_ctx);
    if (result != ALI_CRYPTO_SUCCESS) {
        log_err("update 1th fail\n");
        goto cleanup;
    }
    result = ali_sha256_update(_g_test_data + 13, 128, hash_ctx);
    if (result != ALI_CRYPTO_SUCCESS) {
        log_err("update 2th fail\n");
        goto cleanup;
    }

    result = ali_sha256_final(hash, hash_ctx);
    if (result != ALI_CRYPTO_SUCCESS) {
        log_err("final fail\n");
        goto cleanup;
    }

    if (memcmp(hash, hash_sha256, SHA256_HASH_SIZE)) {
        log_err("hash result not correct!\n");
        result = -1;
        goto cleanup;
    }

    ls_osa_print("====== [HASH] SHA256     OK\n");

cleanup:
    if (hash_ctx) {
        ls_osa_free(hash_ctx);
        hash_ctx = NULL;
    }
    return result;
}
